import { useUserStore } from '@/store/modules/user'
import { deepMerge } from '@/utils'
import { AxiosRequestConfig } from 'axios'
import { AnAxios } from './axios'
import { AxiosTransform, CreateAxiosConfig } from './type/AxiosTypes'
import { ContentTypeEnum } from './type/httpEnum'

const transform: AxiosTransform = {
  requestInterceptors: config => {
    const { headers }: any = config
    headers['token'] = useUserStore().token
    return {
      ...config,
      headers,
    }
  },
  responseInterceptors: res => {
    if (res.data.code !== 1) {
      return [res.data.message, res.data.data]
    }

    return [null, res.data.data]
  },
}

const createAxios = (opt?: AxiosRequestConfig) => {
  const config: CreateAxiosConfig = {
    transform,
    /** 超时时间 */
    timeout: 10 * 1000,
    responseType: 'json',
    headers: {
      'Content-Type': ContentTypeEnum.JSON,
    },
  }
  return new AnAxios(deepMerge(config, opt || {}))
}

export const http = createAxios()
